import { v4 as uuidv4 } from "uuid"

// 检查是否处于离线模式
export function isOfflineMode() {
  // 检查浏览器是否支持 navigator.onLine
  if (typeof navigator !== "undefined" && "onLine" in navigator) {
    return !navigator.onLine
  }
  return false // 默认假设在线
}

// 获取本地存储中的离线模式设置
export function getOfflineModePreference() {
  if (typeof localStorage !== "undefined") {
    return localStorage.getItem("offlineMode") === "true"
  }
  return false
}

// 设置离线模式偏好
export function setOfflineModePreference(value: boolean) {
  if (typeof localStorage !== "undefined") {
    localStorage.setItem("offlineMode", value ? "true" : "false")
  }
}

// 获取所有活跃的投票
export async function getActivePolls() {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Using empty data due to offline mode")
      return []
    }

    // 从 API 获取数据
    try {
      const response = await fetch("/api/polls?active=true")

      if (!response.ok) {
        throw new Error(`Failed to fetch active polls: ${response.status}`)
      }

      const data = await response.json()
      return data.polls || []
    } catch (error) {
      console.error("Error fetching active polls from API:", error)
      return []
    }
  } catch (error) {
    console.error("Error in getActivePolls:", error)
    return []
  }
}

// 获取所有投票（管理员用）
export async function getAllPolls() {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Using empty data due to offline mode")
      return []
    }

    // 从 API 获取数据
    try {
      const response = await fetch("/api/polls")

      if (!response.ok) {
        throw new Error(`Failed to fetch all polls: ${response.status}`)
      }

      const data = await response.json()
      return data.polls || []
    } catch (error) {
      console.error("Error fetching all polls from API:", error)
      return []
    }
  } catch (error) {
    console.error("Error in getAllPolls:", error)
    return []
  }
}

// 获取单个投票详情
export async function getPoll(id: string) {
  try {
    // 从 API 获取数据
    try {
      const response = await fetch(`/api/polls/${id}`)

      if (!response.ok) {
        if (response.status === 404) {
          return null
        }
        throw new Error(`Failed to fetch poll: ${response.status}`)
      }

      const data = await response.json()
      return data.poll || null
    } catch (error) {
      console.error("Error fetching poll from API:", error)
      return null
    }
  } catch (error) {
    console.error("Error in getPoll:", error)
    return null
  }
}

// 创建新投票
export async function createPoll(title: string, description: string, options: string[]) {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Cannot create poll in offline mode")
      throw new Error("无法在离线模式下创建投票")
    }

    // 通过 API 创建投票
    try {
      const response = await fetch("/api/polls", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title,
          description,
          options,
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || "Failed to create poll")
      }

      const data = await response.json()
      return data.poll
    } catch (error: any) {
      console.error("Error creating poll via API:", error)
      throw error
    }
  } catch (error: any) {
    console.error("Error in createPoll:", error)
    throw error
  }
}

// 投票
export async function vote(pollId: string, optionId: string) {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Cannot vote in offline mode")
      throw new Error("无法在离线模式下投票")
    }

    // 生成或获取匿名用户ID
    let voterId = localStorage.getItem("voter_id")
    if (!voterId) {
      voterId = uuidv4()
      localStorage.setItem("voter_id", voterId)
    }

    console.log(`Sending vote request for poll ${pollId}, option ${optionId}, voter ${voterId}`)

    // 通过 API 投票
    try {
      const response = await fetch(`/api/polls/${pollId}/vote`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          optionId,
          voterId,
        }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "Failed to vote")
      }

      // 记录在本地存储
      const votedPolls = JSON.parse(localStorage.getItem("votedPolls") || "[]")
      localStorage.setItem("votedPolls", JSON.stringify([...votedPolls, pollId]))

      return true
    } catch (error: any) {
      console.error("Error voting via API:", error)
      throw error
    }
  } catch (error) {
    console.error("Error in vote:", error)
    throw error
  }
}

// 添加评论
export async function addComment(pollId: string, text: string) {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Cannot add comment in offline mode")
      throw new Error("无法在离线模式下添加评论")
    }

    // 通过 API 添加评论
    try {
      const response = await fetch(`/api/polls/${pollId}/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          text,
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || "Failed to add comment")
      }

      return true
    } catch (error: any) {
      console.error("Error adding comment via API:", error)
      throw error
    }
  } catch (error) {
    console.error("Error in addComment:", error)
    throw error
  }
}

// 更新投票状态（激活/停用）
export async function updatePollStatus(id: string, active: boolean) {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Cannot update poll status in offline mode")
      throw new Error("无法在离线模式下更新投票状态")
    }

    // 通过 API 更新状态
    try {
      const response = await fetch(`/api/polls/${id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          active,
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || "Failed to update poll status")
      }

      return true
    } catch (error: any) {
      console.error("Error updating poll status via API:", error)
      throw error
    }
  } catch (error) {
    console.error("Error in updatePollStatus:", error)
    throw error
  }
}

// 删除投票
export async function deletePoll(id: string) {
  try {
    // 检查是否处于离线模式
    if (isOfflineMode() || getOfflineModePreference()) {
      console.log("Cannot delete poll in offline mode")
      throw new Error("无法在离线模式下删除投票")
    }

    // 通过 API 删除
    try {
      const response = await fetch(`/api/polls/${id}`, {
        method: "DELETE",
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || "Failed to delete poll")
      }

      return true
    } catch (error: any) {
      console.error("Error deleting poll via API:", error)
      throw error
    }
  } catch (error) {
    console.error("Error in deletePoll:", error)
    throw error
  }
}

// 检查用户是否已投票
export function hasUserVoted(pollId: string) {
  const voterId = localStorage.getItem("voter_id")
  if (!voterId) return false

  // 从本地存储检查
  const votedPolls = JSON.parse(localStorage.getItem("votedPolls") || "[]")
  if (votedPolls.includes(pollId)) return true

  return false
}
